<template>
  <el-dialog
    v-if="dialogShow"
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="false"
    custom-class="mydialog"
    width="1200px"
    title="正式交易产品价格变更"
    @close="close"
  >
    <div class="select-client-price">
      <item-title title="选择新终端价" />
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :label-width="formLabelWidth"
        size="small"
        :rules="formRules"
      >
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item
              label="产品名称："
              style="width: 100%;"
            >
              <div class="product-name">{{ productDetail.productPopularName }}-{{ productDetail.approvalNumber }}-{{ productDetail.packSpecs }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="终端价："
              prop="terminalPrice"
            >
              <app-price-popover
                ref="pricePop"
                :props-product="{productId: formData.id,terminalType:'',region: []}"
                position="bottom-start"
                @confirm="selectPrice"
              >
                <div style="display:flex;flex-wrap:nowrap;">
                  <el-select
                    v-model="formData.terminalPrice"
                    style="flex:1;"
                    placeholder="选择终端价"
                    clearable
                    @focus="priceFocus"
                    @clear="priceClear"
                  >
                    <template #empty />
                  </el-select>
                  <span
                    v-if="formData?.sellUnit"
                    style="margin-left:4px;"
                  >元 / {{ getLabel('sell_unit',formData?.sellUnit) }}</span>
                </div>
              </app-price-popover>
            </el-form-item>
          </el-col>
          <el-col
            v-if="formData.priceNumber"
            :span="12"
          >
            <el-form-item
              label="价格编号："
              style="width: 100%;"
              prop="priceNumber"
            >
              <div>{{ formData.priceNumber }}</div>
            </el-form-item>
          </el-col>
          <el-col
            v-if="formData.accessMode"
            :span="12"
          >
            <el-form-item
              label="准入模式："
              style="width: 100%;"
              prop="accessMode"
            >
              <span>{{ getLabel('access_mode',formData.accessMode) }}</span>
            </el-form-item>
          </el-col>
          <el-col
            v-if="formData.region?.length"
            :span="12"
          >
            <el-form-item
              class="form-item"
              label="适用地区："
              style="width: 100%;"
              prop="area"
            >
              <div>
                <area-list-view :areas="formData.region" />
              </div>
            </el-form-item>
          </el-col>
          <el-col
            v-if="formData.terminalType"
            :span="12"
          >
            <el-form-item
              class="form-item"
              label="适用终端："
              style="width: 100%;"
              prop="terminalType"
            >
              <div>{{ getLabel('app_mode',formData.terminalType) }}</div>
            </el-form-item>
          </el-col>
          <el-col
            v-if="formData.marketPrice"
            :span="12"
          >
            <el-form-item
              class="form-item"
              label="市场价："
              style="width: 100%;"
              prop="marketPrice"
            >
              <div><span>{{ formData.marketPrice }}</span><span v-if="formData?.sellUnit">元 / {{ getLabel('sell_unit',formData?.sellUnit) }}</span></div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div
      class="select-client-list"
      style="margin-bottom: 20px;"
    >
      <item-title title="变更终端列表">
        <template #btn>
          <el-button
            class="border-btn"
            size="mini"
            @click="removeAllClient"
          >全部移除</el-button>
          <el-button
            type="primary"
            class="main-btn"
            size="mini"
            @click="addClient"
          >添加终端</el-button>
        </template>
      </item-title>
      <div class="table-list">
        <el-table
          header-cell-class-name="table-header"
          :data="clientListData"
          border
          :max-height="350"
        >
          <el-table-column
            label="终端编号"
            prop="terminalNo"
            header-align="center"
            align="center"
            :min-width="100"
            show-overflow-tooltip
            fixed="left"
          >
            <template #default="scope">{{ scope.row.terminalNo }}</template>
          </el-table-column>
          <el-table-column
            label="终端名称"
            prop="terminalName"
            header-align="center"
            :min-width="140"
            show-overflow-tooltip
            fixed="left"
          />
          <el-table-column
            label="所在地区"
            header-align="center"
            :min-width="140"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div>{{ scope.row.provinceName }} / {{ scope.row.cityName }} / {{ scope.row.areaName }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="原市场价（元）"
            header-align="center"
            align="center"
            :min-width="120"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div>{{ scope.row.productInfoDetail.marketPrice }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="原终端价（元）"
            prop="terminalPrice"
            header-align="center"
            align="center"
            :min-width="120"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div>{{ scope.row.terminalPrice }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="准入模式"
            prop="accessMode"
            header-align="center"
            align="center"
            :min-width="120"
            show-overflow-tooltip
          >
            <template #default="{row}">
              <span>{{ getLabel('access_mode',row.accessMode) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="原关联产品价格"
            prop="priceNumber"
            header-align="center"
            align="center"
            :min-width="140"
            show-overflow-tooltip
          />
          <el-table-column
            label="营销模式"
            prop="sellMode"
            header-align="center"
            align="center"
            :min-width="120"
            show-overflow-tooltip
          >
            <template #default="scope">
              <span v-if="scope.row?.sellMode !== 'direct'">
                {{ scope.row?.agentAttribute === '1' ?'独家招商':'精细招商' }}
              </span>
              <span v-else> 终端直销</span>
            </template>
          </el-table-column>
          <el-table-column
            label="渠道客户名称"
            header-align="center"
            :min-width="140"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div v-if="scope.row.agentDetail?.agentType==='agent'">
                {{ scope.row.agentDetail?.agentName }}
              </div>
              <div v-if="scope.row.agentDetail?.agentType==='agent_person'">
                {{ scope.row.agentDetail?.userName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="操作"
            width="100"
            header-align="center"
            align="center"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                type="text"
                @click="removeItem(scope.row, scope.$index)"
              >移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加中断 -->
    <add-client
      ref="addClientRef"
      @selectSuccess="selectSuccess"
    />

    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="confirm"
        >提交审核</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {defineComponent, getCurrentInstance, inject, reactive, ref, toRefs,} from 'vue'
import addClient from './addClient.vue'
import area from '@/utils/area.js'
import {crmStore} from '@CRM/store'
import {useRoute} from 'vue-router'

export default defineComponent({
  name: 'ChangeClientPrice',
  components: { addClient },
  emits: ['onSuccess'],
  setup(props, context) {
    const route = useRoute()
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    const formRef = ref(null)
    const pricePop = ref(null)
    const addClientRef = ref(null)
    const citys = area
    var reactiveData = reactive({
      productDetail: null,
      accessModeOptions:
        crmStore.getters['dictionary/getDictionary']['access_mode'],
      terminalTypeOptions:
        crmStore.getters['dictionary/getDictionary']['app_mode'],
      formData: {
        id: route.query.productId ? Number(route.query.productId) : 0,
        terminalPrice: '',
        priceNumber: '',
        accessMode: '',
        terminalType: '',
        marketPrice: null,
      },
      productPriceId: 0,
      clientListData: [],
      priceData: null,
    })
    var formRules = reactive({
      terminalPrice: [
        { required: true, message: '请请选择终端价', trigger: 'change' },
      ],
    })
    var formLabelWidth = ref(100)
    var dialogShow = ref(false)
    const open = (productDetail) => {
      reactiveData.productDetail = productDetail
      // reactiveData.formData = productDetail
      reactiveData.accessModeOptions =
        crmStore.getters['dictionary/getDictionary']['access_mode']

      dialogShow.value = true
    }
    const close = () => {
      formRef.value.resetFields()
      reactiveData.priceData = null
      dialogShow.value = false
    }
    const confirm = () => {
      if (reactiveData.clientListData.length === 0) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请选择终端',
        })
        return
      }
      formRef.value.validate((valid) => {
        if (valid) {
          var subdata = {
            newProductPriceId: reactiveData.productPriceId,
            standardIds: reactiveData.clientListData.map((p) => p.id),
          }
          api.product.PURCHASE_PRICE_CHANGE(subdata).then((res) => {
            if (res.code === 0) {
              console.log(res.data)
              currentInstance.proxy.customMessage({
                type: 'success',
                message: '交易产品价格变更成功',
              })
              context.emit('onSuccess')
              close()
            } else {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: res.msg,
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    const selectSuccess = (val) => {
      // 此处需要去重
      reactiveData.clientListData = val
    }
    const addClient = () => {
      console.log('添加终端')
      if (reactiveData.productPriceId === 0) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请先选择终端价',
        })
        return
      }
      const objdata = {
        productId: Number(route.query.productId),
        priceData: reactiveData.priceData,
      }
      addClientRef.value.open(objdata)
    }
    const removeItem = (row, index) => {
      reactiveData.clientListData.splice(index, 1)
    }
    const removeAllClient = () => {
      reactiveData.clientListData.splice(0, reactiveData.clientListData.length)
    }
    const selectPrice = (val) => {
      console.log('333333', val)
      reactiveData.priceData = val
      reactiveData.productPriceId = val.id
      reactiveData.formData.terminalPrice = val.terminalPrice
      reactiveData.formData.sellUnit = val.sellUnit
      reactiveData.formData.priceNumber = val.priceNumber
      reactiveData.formData.accessMode = val.accessMode
      reactiveData.formData.region = val.region
      reactiveData.formData.terminalType = val.terminalType
      reactiveData.formData.marketPrice = val.marketPrice
      console.log(reactiveData.formData.region)
    }
    const priceFocus = (val) => {
      if (val) {
        pricePop.value.openPopover()
      } else {
        console.log(545)
      }
    }
    const priceClear = () => {
      reactiveData.priceData = null
      reactiveData.productPriceId = 0
      reactiveData.formData = {
        id: route.query.productId ? Number(route.query.productId) : 0,
        terminalPrice: '',
        priceNumber: '',
        accessMode: '',
        terminalType: '',
        marketPrice: null,
        sellUnit: '',
        region: [],
      }
    }
    return {
      formRef,
      addClientRef,
      pricePop,
      citys,
      ...toRefs(reactiveData),
      formRules,
      formLabelWidth,
      dialogShow,
      open,
      close,
      confirm,
      selectSuccess,
      addClient,
      removeItem,
      removeAllClient,
      priceFocus,
      priceClear,
      selectPrice,
    }
  },
})
</script>

